package com.hc.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hc.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

//@RestController
@Controller
@RequestMapping("/user")
@DefaultProperties(defaultFallback = "fallBack")
public class ClientController {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${test.name}")
    private  String name;


    @RequestMapping("/getOne")
    @ResponseBody
    public User getOne(){
        return new User(1,"张三",18);
    }

    @RequestMapping("/getList")
    @ResponseBody
    /*豪猪熔断*/
    @HystrixCommand(fallbackMethod = "fallBack")
    public String getList() throws JsonProcessingException {
        System.out.println("动态的name================="+name);

        String url = "http://localhost:9091/user/getList";
        //获取eureka中注册的user-service实例列表
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("HXM-user-service");
        ServiceInstance serviceInstance = serviceInstanceList.get(0);
        url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort()
                + "/user/getList";
        System.out.println(url);

        /*使用负载均衡*/
        url="http://HXM-USER-SERVICE/user/getList";
        System.out.println(url);
        List<User> userList = restTemplate.getForObject(url, List.class);
        return new ObjectMapper().writeValueAsString(userList);
    }

    public String fallBack(){
        return "网络拥挤,请稍后重试";
    }
}
